<?php
/* @var $this SnapshotController */
/* @var $model Project */

if($project == null){
	$this->breadcrumbs=array(
			Yii::t('monitor','Snapshot List')=>array('index'),
			$county->name
	);
	$displayTitle = $county->name;
} else {
	$this->breadcrumbs=array(
			Yii::t('monitor','Snapshot List')=>array('index'),
			$county->name => array('view', 'cid'=>$county->id),
			$project->name
	);
	$displayTitle = $project->name;
}

?>

<style type="text/css">
#project-grid-snapshot img {
    display: block;
    margin-left: auto;
    margin-right: auto;
}
</style>

<script type="text/javascript">
	function initialize() {
	  	var map = new BMap.Map('baiduMap');
	  	var point = new BMap.Point(101.898517,30.116144);
	    map.centerAndZoom(point, 7);
//	  	map.enableScrollWheelZoom();

	    var bdary = new BMap.Boundary();
	    bdary.get("<?php echo $county->name; ?>", function(rs){       //获取行政区域
	        map.clearOverlays();        //清除地图覆盖物       
	        var count = rs.boundaries.length; //行政区域的点有多少个
	        for(var i = 0; i < count; i++){
	            var ply = new BMap.Polygon(rs.boundaries[i], {strokeWeight: 2, strokeColor: "#ff0000"}); //建立多边形覆盖物
	            map.addOverlay(ply);  //添加覆盖物
	            map.setViewport(ply.getPath());    //调整视野         
	        } 
<?php

	$markerIndex = 0;
	foreach($county->projects as $eachData) {
		echo 'var marker' . $markerIndex . ' = new BMap.Marker(new BMap.Point(' . $eachData->longitude . ', ' . $eachData->latitude . '));';
		echo 'map.addOverlay(marker' . $markerIndex . ');';
		echo 'var infoWindow' . $markerIndex . ' = new BMap.InfoWindow("' . Yii::t('monitor','Project Description') . ': ' . $eachData->description . '",
																					{width:200,title:"(<a href=\"' . $this->createUrl('snapshot/view', array('cid'=>$eachData->county->id, 'pid'=>$eachData->id)) . '\">' . Yii::t('monitor','Click to see snapshot') . '</a>)<br/>' . $eachData->name . '"});';
		echo 'marker' . $markerIndex . '.addEventListener("click", function(){this.openInfoWindow(infoWindow' . $markerIndex . ');});';
		echo 'marker' . $markerIndex . '.addEventListener("mouseover", function(){changeTips("' . $eachData->name . '"); });';
		echo 'marker' . $markerIndex . '.addEventListener("mouseout", function(){changeTips("' . Yii::t('monitor','Please select project on the map.') . '"); });';
		$markerIndex++;
	}
?>
             
	    });   
	}
	 
	function loadScript() {
	  var script = document.createElement("script");
	  script.src = "http://api.map.baidu.com/api?v=2.0&ak=5a90faa9eadcf6b86a4165ea8f218b47&callback=initialize";//此为v2.0版本的引用方式
	  // http://api.map.baidu.com/api?v=1.5&ak=您的密钥&callback=initialize"; //此为v1.4版本及以前版本的引用方式
	  document.body.appendChild(script);
	}
	 
	window.onload = loadScript;
	
	function changeTips(tipContent) {
		$("#projectTips").html(tipContent);
	}
</script>
<div class="row-fluid hidden-phone">
	<div class="span12">
		<div class="alert alert-info">
			<h1 class="text-center"> <?php echo $displayTitle . Yii::t('monitor','construction site snapshots'); ?> </h1>
		</div>
	</div>
</div>
<div class="row-fluid">
	<div class="span6">	
<?php 
	if($project == null) {
		//Display the projects list
		$this->widget('bootstrap.widgets.TbGridView',array(
				'id'=>'project-grid-snapshot',
				'type'=>'striped bordered condensed',
				'template'=>"{items}",
				'dataProvider'=>$dataProvider,
				'selectionChanged'=>'function(id){loadSnapshot();}',
				'columns'=>array(
						array(
								'name'=>'name', 'header'=>$county->name,
								'type'=>'raw',
								'value'=>'CHtml::link("$data->name","index.php?r=snapshot/view&cid=".CHtml::encode('.$county->id.')."&pid=".CHtml::encode($data->id))',
								'htmlOptions'=>array('style'=>'text-align:center;cursor:pointer;'), 'headerHtmlOptions'=>array('style'=>'text-align:center')),
				),
		)); 
	} else {
		//Search the numbers of IP cameras belonging to this project
		$cameraNum = count($project->camerases);
		//Display the Snapshot here
		$snapshotContent = '';
		$snapshotContent .= '<div class="alert alert-info">';
		$snapshotContent .= '<div class="row-fluid">';
		$snapshotContent .= '	<div class="span12">';
		$snapshotContent .= '		<div>';
		$snapshotContent .= '	   		<h3 class="text-center">' . $county->name . '</h3>';
		$snapshotContent .= '	   		<h5 class="text-center">' . $project->name . '</h5>';
		$snapshotContent .= '   	</div>';
		$snapshotContent .= '   </div>';
		$snapshotContent .= '</div>';
		$snapshotContent .= '<div class="row-fluid">';
		if($cameraNum < 7) {
			foreach($project->camerases as $eachCamera) {
				$snapshotContent .= '<div class="span' . (12/$cameraNum) . '">';
				$snapshotContent .= copyLatestImage($eachCamera->cam_id);
				$snapshotContent .= '</div>';
			}			
		} else {
			foreach($project->camerases as $eachCamera) {
				$snapshotContent .= '<div class="span1">';
				$snapshotContent .= copyLatestImage($eachCamera->cam_id);
				$snapshotContent .= '</div>';
			}
		}
	    $snapshotContent .= '</div>';
	    $snapshotContent .= '<div class="row-fluid">';
	    $snapshotContent .= '	<div class="span12">';
	    $snapshotContent .= '		<div class="text-center">';
	    $snapshotContent .= '	   		<button class="btn btn-mini btn-link" type="button">' . Yii::t('monitor','Refresh Snapshot') . '</button>';
	    $snapshotContent .= '	   		<p>' . Yii::t('monitor','Snapshot will be automatically refreshed every 1 minute.') . '</p>';
	    $snapshotContent .= '   	</div>';
	    $snapshotContent .= '   </div>';
	    $snapshotContent .= '</div>';
	    
	    
	    $snapshotContent .= '</div>';
	    echo $snapshotContent;
	}
	
	function copyLatestImage($camId) {
		$dir = '/opt/ipcam/' . $camId . '/';
		$fileTimeArr = array();
		// Open a known directory, and proceed to read its contents
		if (is_dir($dir)) {
			if ($dh = opendir($dir)) {
				while (($file = readdir($dh)) !== false) {
					if ($file != "." && $file != "..") {
						//	The file name example: 00_0C_5D_75_6F_95_EST-005052-JZUXL_0_20131217110132_2.jpg
						//	Try to retrieve the time included in the file name like: 20131217110132
						$fileTime = strstr($file, $camId);
						$fileTime = substr($fileTime, 3 + strlen($camId), 14);
						$fileTimeArr[$fileTime] = $file;
						//	echo "filename: $file : fileTime: $fileTime : filetype: " . filetype($dir . $file) . "\n";
					}
				}
				closedir($dh);
			}
		}
		//Sort the time of the files to get the last one to display
		ksort($fileTimeArr);				
		//Copy the latest image to the Monitor specific folder
		copy( $dir . end($fileTimeArr), '/opt/monitor/images/' . $camId . '.' . pathinfo($dir . end($fileTimeArr), PATHINFO_EXTENSION) );
		
		$lastImageTime = strstr(end($fileTimeArr), $camId);
		$lastImageTime = substr($lastImageTime, 3 + strlen($camId), 14);
		$lastImageTimeStr = substr($lastImageTime, 0, 4) . '-' . substr($lastImageTime, 4, 2) . '-' . substr($lastImageTime, 6, 2)
									. ' ' . substr($lastImageTime, 8, 2) . ':' . substr($lastImageTime, 10, 2) . ':' . substr($lastImageTime, 12, 2);
		
		$snapshotImage = '';
		$snapshotImage .= '	<div class="row-fluid">';
		$snapshotImage .= '		<div id="project-grid-snapshot" class="media">';
		$snapshotImage .= '	   		<img class="media-object img-polaroid" style="-webkit-user-select: none" src="' . Yii::app()->baseUrl . '/images/' . $camId . '.' . pathinfo($dir . end($fileTimeArr), PATHINFO_EXTENSION) . '">';
		$snapshotImage .= '   	</div>';
		$snapshotImage .= '	</div>';
		$snapshotImage .= '	<div class="row-fluid">';
		$snapshotImage .= '		<p class="text-center">' . $lastImageTimeStr . '</p>';
		$snapshotImage .= '	</div>';
		return $snapshotImage;
	}	

?>		
	</div>
	<div class="span6">
		<div class="row-fluid">
			<div class="span12">
				<div id="baiduMap" style="width: 100%;min-height: 370px;overflow: hidden;margin:0;"></div>
			</div>
		</div>
		<div class="row-fluid">
			<div class="span12">
				<div id="projectTips" class="alert alert-info" style="text-align:center"><?php echo Yii::t('monitor','Please select project on the map.');?></div>
			</div>
		</div>	</div>
</div>